package org.yejiali.job;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.yejiali.domain.entity.Article;
import org.yejiali.mapper.ArticleMapper;
import org.yejiali.service.ArticleService;
import org.yejiali.util.RedisCache;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author:yejiali
 * @Date:2025/3/5-03-05-10:38
 * @Decsription:org.yejiali.job
 * @Version:1.0
 */
@Component
public class UpdateViewCountJob {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleService articleService;
    /**
     * 实时更新博客浏览量
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void updateViewCount(){
        System.out.println("定时");
        //将redis中的浏览量更新到数据库中
        Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCountMap");
       List<Article> article=viewCountMap.entrySet()
                .stream()  //将键值对转化为Article对象，并对构造方法中的参数进行类型转换
                .map(entry->new Article(Long.valueOf(entry.getKey()),entry.getValue().longValue()))
                .collect(Collectors.toList());
        articleService.updateBatchById(article);


    }
}
